package com.leo.chapter13;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author xuexiaolei
 * @version 2017年10月19日
 */
public class Test {
    Lock lock = new ReentrantLock();
    /************************ 带有时间限制的锁 ****************************************/
    public boolean trySendOnSharedLine(String message, long timeout, TimeUnit unit) throws InterruptedException{
        long nanosToLock = unit.toNanos(timeout) - estimatedNanosToSend(message);
        if (!lock.tryLock(nanosToLock, TimeUnit.NANOSECONDS)){
            return false;
        }
        try {
            return sendOnSharedLine(message);
        }finally {
            lock.unlock();
        }
    }

    /************************ 可中断的锁 ****************************************/
    public boolean sendOnSharedLine2(String message) throws InterruptedException {
        lock.lockInterruptibly();
        try {
            return sendOnSharedLine(message);
        }finally {
            lock.unlock();
        }
    }


    /************************ 不重要的方法 ****************************************/
    private boolean sendOnSharedLine(String message) {
        return true;
    }
    private long estimatedNanosToSend(String message) {
        return 0;
    }
}
